package cn.sofwin.core.utils.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化工具
 * @author LetCode
 * @since 1.0
 *
 */
public class SerializeUtils {
	/**
	 * 序列化对象
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		byte[] bytes = null;
		
		if(object != null){
			ObjectOutputStream oos = null;
			ByteArrayOutputStream baos = null;
			try {
				baos = new ByteArrayOutputStream();
				oos = new ObjectOutputStream(baos);
				oos.writeObject(object);
				oos.flush();
				bytes = baos.toByteArray();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if(oos != null)
						oos.close();
					if(baos != null)
						baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bytes;
	}

	/**
	 * 反序列化对象
	 * @param bytes
	 * @return
	 */
	public static Object unserialize(byte[] bytes) {
		Object object = null;
		
		if(bytes != null){
			ByteArrayInputStream bais = null;
			ObjectInputStream ois = null;
			try {
				bais = new ByteArrayInputStream(bytes);
				ois = new ObjectInputStream(bais);
				object = ois.readObject();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if(ois != null)
						ois.close();
					if(bais != null)
						bais.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return object;
	}
}
